<?php

class Phonebook extends MX_Controller {

	private $_title;
	
	public function __construct()
	{
		parent::__construct();		
		
		$this->load->helper(array('form', 'url'));
		
		$this->load->model('phonebook_model', 'phonebook');
		
		$this->lang->load('phonebook/phonebook', 'english');
		
		$this->_title = $this->lang->line('title');
	}
	
	public function index()
	{
		if (!$this->session->userdata('session_loggedin')) {
			redirect('user/login/' . $this->core->encode($this->uri->uri_string()));
		}
		
		$data['title'] = $this->_title;
		$data['heading_title'] = $this->lang->line('list_heading_title');
		$data['content'] = 'index';
		
		$this->load->library('pagination');
		
		$limit = 15;
		$offset = $this->uri->segment(3);
		
		$search = '';
		
		if ($this->input->get('q') && $this->input->get('q') != '') {
			$search = $this->input->get('q');
			$data['search'] = $search;
		}
		
		$data['search'] = $search;
				
		$results = $this->phonebook->getAll($limit, $offset, $search);
		
		$this->load->library('table');
		
		$tmpl = array(
			'table_open'		=> '<table class="tblPhonebookList" cellpadding="4" cellspacing="0" align="center">',
			'row_start'    		=> '<tr class="zebra">',
			'row_end'       	=> '</tr>',
			'cell_start'    	=> '<td>',
			'cell_end'      	=> '</td>',
			'row_alt_start'     => '<tr>',
            'row_alt_end'       => '</tr>',
            'cell_alt_start'    => '<td>',
            'cell_alt_end'      => '</td>',
			'table_close'		=> '</table>'
		);
		
		$this->table->set_template($tmpl);
		
		$this->table->set_heading('#', 'Name', 'Mobile 1', 'Mobile 2', 'Other No', 'Address', 'Email', 'Description', 'Action');
		
		$no = 0;
		foreach ($results as $result) {
			$this->table->add_row(
				array('data' => ($no + $offset + 1) . '.', 'width' => 20, 'valign' => 'top'),
				array('data' => anchor('phonebook/photos/' . $result['id'] . '/' . $offset, $result['name']), 'width' => 150, 'valign' => 'top'), 
				array('data' => $result['mobile1'], 'width' => 100, 'valign' => 'top'),
				array('data' => $result['mobile2'], 'width' => 100, 'valign' => 'top'),
				array('data' => $result['other_no'], 'width' => 100, 'valign' => 'top'),
				array('data' => $result['address'], 'width' => 200, 'valign' => 'top'),
				array('data' => $result['email'], 'valign' => 'top'),
				array('data' => $result['desc'], 'width' => 200),
				array('data' => anchor('phonebook/edit/' . $result['id'] . '/' . $offset, 'Edit') . ' | ' .  anchor('phonebook/delete/' . $result['id'] . '/' . $offset, 'Delete', 'onclick="return confirm(\'Are you sure you want to delete?\')"'), 'width' => 80, 'valign' => 'top', 'nowrap' => 'nowrap')
			);
			
			$no++;
		}
		
		$data['table'] = $this->table->generate();
		
		$config = array(
			'base_url'		=> $this->config->base_url('phonebook/index'),
			'total_rows'	=> $this->phonebook->getTotalRows($search),
			'per_page'		=> $limit
		);
		
		$this->pagination->initialize($config);
		$data['pagination'] = $this->pagination->create_links();
		
		$this->load->view('template', $data);
	}
	
	public function add()
	{
		if (!$this->session->userdata('session_loggedin')) {
			redirect('user/login/' . $this->core->encode($this->uri->uri_string()));
		}
		
		$data['heading_title'] = $this->lang->line('add_heading_title');
		$data['form_action'] = 'phonebook/add';
		
		$this->load->library('form_validation');
		
		$this->form_validation->set_rules('name', 'Name', 'required');
		$this->form_validation->set_rules('email', 'Email', 'valid_email');
		
		if ($this->form_validation->run() == TRUE) {
			$name = $this->input->post('name');
			$mobile1 = $this->input->post('mobile1');
			$mobile2 = $this->input->post('mobile2');
			$otherPhone = $this->input->post('otherPhone');
			$address = $this->input->post('address');
			$email = $this->input->post('email');
			$description = $this->input->post('description');
			
			$data = array(
				'name'			=> htmlentities($name),
				'mobile1'		=> $mobile1,
				'mobile2'		=> $mobile2,
				'other_no'		=> $otherPhone,
				'address'		=> $address,
				'email'			=> $email,
				'desc'			=> nl2br($description),
				'time_added'	=> date('Y-m-d H:i:s')
			);
			
			$this->phonebook->insert($data);
			
			redirect('phonebook');
		}
		
		$this->getForm($data);
	}
	
	public function edit()
	{
		if (!$this->session->userdata('session_loggedin')) {
			redirect('user/login/' . $this->core->encode($this->uri->uri_string()));
		}
		
		$id = $this->uri->segment(3);
		$pageOffset = $this->uri->segment(4);
		
		$data['heading_title'] = $this->lang->line('edit_heading_title');
		$data['form_action'] = 'phonebook/edit/' . $id . '/' . $pageOffset;
		
		$result = $this->phonebook->getDataById($id);
		$data['form']['name'] = $result['name'];
		$data['form']['mobile1'] = $result['mobile1'];
		$data['form']['mobile2'] = $result['mobile2'];
		$data['form']['other_phone'] = $result['other_no'];
		$data['form']['address'] = $result['address'];
		$data['form']['email'] = $result['email'];
		$data['form']['desc'] = str_replace('<br />', "", $result['desc']);
		
		$this->load->library('form_validation');
		
		$this->form_validation->set_rules('name', 'Name', 'required');
		$this->form_validation->set_rules('email', 'Email', 'valid_email');
		
		if ($this->form_validation->run() == TRUE) {
			$name = $this->input->post('name');
			$mobile1 = $this->input->post('mobile1');
			$mobile2 = $this->input->post('mobile2');
			$otherPhone = $this->input->post('otherPhone');
			$address = $this->input->post('address');
			$email = $this->input->post('email');
			$description = $this->input->post('description');
			
			$data = array(
				'name'			=> htmlentities($name),
				'mobile1'		=> $mobile1,
				'mobile2'		=> $mobile2,
				'other_no'		=> $otherPhone,
				'address'		=> $address,
				'email'			=> $email,
				'desc'			=> nl2br($description),
				'time_edited'	=> date('Y-m-d H:i:s')
			);
			
			$this->phonebook->update($data, $id);
			
			redirect('phonebook/index/' . $pageOffset);
		}
		
		$this->getForm($data);
	}
	
	private function getForm($data = array())
	{
		$data['title'] = $this->_title;		
		$data['content'] = 'form';
		
		$this->load->view('template', $data);
	}
	
	public function delete()
	{
		if (!$this->session->userdata('session_loggedin')) {
			redirect('user/login');
		}
		
		$id = $this->uri->segment(3);
		$pageOffset = $this->uri->segment(4);
		
		$this->phonebook->delete($id);
		$this->phonebook->deletePhoto($id);
		
		redirect('phonebook/index/' . $pageOffset);
	}
	
	public function photos()
	{
		if (!$this->session->userdata('session_loggedin')) {
			redirect('user/login/' . $this->core->encode($this->uri->uri_string()));
		}
		
		$id = $this->uri->segment(3);
		$pageOffset = $this->uri->segment(4);
		
		$result = $this->phonebook->getDataById($id);
		
		$data['title'] = $this->_title;
		$data['heading_title'] = sprintf($this->lang->line('photos_heading_title'), $result['name']);
		$data['content'] = 'photos';
		$data['back'] = $pageOffset ? base_url('phonebook/index/' . $pageOffset) : base_url('phonebook');
		$data['add'] = base_url('phonebook/add_photo/' . $id . '/' . $pageOffset);

		$results = $this->phonebook->getPhotos($id);
		
		$data['photos'] = array();
		
		foreach ($results as $result) {
			$data['photos'][] = array(
				'id'	=> $result['id'],
				'photo' => base_url('phonebook/image/' . $result['id'])
			);
		}
		
		$data['total'] = $this->phonebook->getTotalPhotos($id);
		
		$this->load->view('template', $data);
	}
	
	public function image()
	{
		if (!$this->session->userdata('session_loggedin')) {
			redirect('user/login');
		}
		
		$id = $this->uri->segment(3);
		
		$result = $this->phonebook->getImage($id);
		
		if ($result) {
			$this->output->set_header('Content-Type: ' . $result['photo_filetype']);
			//$this->output->set_header('Expires: '.gmdate('D, d M Y H:i:s', time()+14*24*60*60) . ' GMT');
			$this->output->set_header('Cache-Control: no-Store, no-Cache, must-revalidate');
			$this->output->set_output($result['photo_blob']);
		} else {
			show_404();
		}
	}
	
	public function add_photo()
	{
		if (!$this->session->userdata('session_loggedin')) {
			redirect('user/login/' . $this->core->encode($this->uri->uri_string()));
		}
		
		$id = $this->uri->segment(3);
		$pageOffset = $this->uri->segment(4);
		
		if (!$id) {
			show_404();
		}
		
		$result = $this->phonebook->getDataById($id);
		
		$data['title'] = $this->_title;
		$data['heading_title'] = sprintf($this->lang->line('add_photos_heading_title'), $result['name']);
		$data['content'] = 'add_photo';
		
		$this->load->helper('form');
		$this->load->library('form_validation');
		
		$config = array(
			'upload_path'	=> FCPATH . 'data/temp/',
			'allowed_types'	=> 'jpg|png|gif'
		);
	
		$this->load->library('upload', $config);
		
		if ($this->input->post('cmd') == 'upload') {
			if ($this->upload->do_upload('file')) {
				$data = array('upload_data' => $this->upload->data());
				$fullPath = $data['upload_data']['full_path'];
				$fileType = $data['upload_data']['file_type'];
				$fileExt = end(explode('.', $data['upload_data']['file_ext']));
				$fileSize = $data['upload_data']['file_size'];
				
				$image = file_get_contents($fullPath);
				
				$data = array(
					'phonebook_id'		=> $id,
					'photo_filetype'	=> $fileType,
					'photo_ext'			=> $fileExt,
					'photo_filesize'	=> $fileSize,
					'photo_blob'		=> $image
				);
				
				$this->phonebook->addPhoto($data);
				
				@unlink($fullPath);
				
				redirect('phonebook/photos/' . $id . '/' . $pageOffset);
			} else {
				$this->form_validation->set_error($this->upload->display_errors());
			}
		}
		
		$this->load->view('template', $data);
	}
	
	public function delete_photo()
	{
		if (!$this->session->userdata('session_loggedin')) {
			redirect('user/login');
		}
		
		$pid = $this->uri->segment(3);
		$phonebookId = $this->uri->segment(4);
		$pageOffset = $this->uri->segment(5);
		
		if (!$pid) {
			show_404();
		}
		
		$this->phonebook->deleteSelectedPhoto($pid);
		
		redirect('phonebook/photos/' . $phonebookId . '/' . $pageOffset);
	}
}